package com.kzx.controller;

import com.kzx.pojo.SwitchOptions;
import com.kzx.util.CADUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kongz
 * @version 1.0 2021/8/3 15:58
 * @description TODO
 */
@Controller
public class DwgToSvgController {

    @GetMapping("/")
    public String index(HttpSession session) {
        session.setAttribute("fileList", new ArrayList<String>());
        session.setAttribute("msg", "0");
        return "dwgToSvg";
    }

    @GetMapping("/toDwgToSvg")
    public String toDwgToSvg() {
        return "dwgToSvg";
    }

    @PostMapping("/upload")
    public String DwgToSvg(@RequestParam("file") CommonsMultipartFile file,
                           HttpServletRequest request, SwitchOptions switchOptions, HttpSession session) throws IOException {
        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        String svgPath = request.getServletContext().getRealPath("/svg");
        File file1 = new File(svgPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);

        if (!judgeDwg(file.getOriginalFilename())) {
            session.setAttribute("msg", "文件非dwg文件!");
            return "dwgToSvg";
        }

        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

        String prePath = request.getServletContext().getRealPath("");
        String targetFileName = CADUtils.dwgToSvg(file.getOriginalFilename(), switchOptions, prePath);
        List<String> fileList = (List<String>) session.getAttribute("fileList");
        fileList.add(targetFileName);
        session.setAttribute("fileList", fileList);

        return "dwgToSvg";
    }

    @GetMapping("/download/{fileName}")
    public String downloads(HttpServletRequest request,
                            @PathVariable("fileName")String fileName,
                            HttpServletResponse response) throws IOException {
        //要下载的图片地址
        String  path = request.getServletContext().getRealPath("/svg");

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path,fileName);
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return "dwgToSvg";
    }

    public static boolean judgeDwg(String fileName) {
        //获取最后一个.的位置
        int lastIndexOf = fileName.lastIndexOf(".");
        //获取后缀名
        String suffix = fileName.substring(lastIndexOf);
        return suffix.equals(".dwg");
    }


}
